# coding:utf-8

from configparser import ConfigParser
from bs4 import BeautifulSoup
import requests
import os
import base64
import traceback


class Evernote2Mrdoc():
    def __init__(self):
        self.mrdoc_url = MRDOC_URL
        self.mrdoc_token = MRDOC_TOKEN
        self.base_path = BASE_PATH
        self.projects = {}
        self.toc_item_list = []
        self.toc_id_map = {}
        self.total_doc = 0
        self.total_img = 0

    def get_projects(self):
        resp = requests.get(self.mrdoc_url + '/api/get_projects/?token=' + self.mrdoc_token).json()
        if resp['status']:
            print(">>>文集列表：")
            projects = resp['data']
            for p in projects:
                print("{} - {}".format(p['id'],p['name']))
                self.projects[str(p['id'])] = p['name']
        else:
            print("[x]读取文集列表失败")
            return False

    def get_content(self,file_path):
        with open(os.path.join(self.base_path,file_path),'r+',encoding='utf-8') as file:
            soup = BeautifulSoup(file.read(),'lxml')
            # src_tag = soup.find_all(lambda tag: tag.has_attr("src"))  # 查找所有包含src的标签
            img_tag = soup.find_all('img',src=True)
            # print(src_tag)

            # 替换HTML文本中静态文件的相对链接为绝对链接
            for img in img_tag:
                img_src = os.path.join(self.base_path,img['src'])
                if os.path.exists(img_src) is False:
                    continue
                is_upload_img = self.upload_img(path=img_src)
                if 'success' in is_upload_img.keys() and is_upload_img['success'] == 1:
                    print("+转存图片成功：", img_src)
                    self.total_img += 1
                    img['src'] = is_upload_img['url']

            # 新建文档
            doc_info = {
                'pid': self.project_id,
                'title': file_path[:-5],
                'doc': str(soup),
                'editor_mode': 3,
            }
            doc_created = self.create_doc(info=doc_info)
            if doc_created['status']:
                self.total_doc += 1
                print("+已导入文档：", file_path[:-5])

    # 新建文档
    def create_doc(self, info):
        resp = requests.post(self.mrdoc_url + "/api/create_doc/?token=" + self.mrdoc_token, data=info)
        return resp.json()

    # 上传图片
    def upload_img(self,path):
        with open(path,'rb') as img:
            img_base = base64.b64encode(img.read())
            resp = requests.post(self.mrdoc_url + "/api/upload_img/?token="+self.mrdoc_token,data={"data":img_base})
            # print(resp.json())
            return resp.json()

    def work(self):
        try:
            self.get_projects()
            self.project_id = input("请输入需要目标文集的ID：")
            if self.project_id not in self.projects.keys():
                print("[x]选择的文集不存在！")
                return False
            print(">>>你选择导入的目标文集为：《{}》".format(self.projects[self.project_id]))
            for p in os.listdir(self.base_path):
                is_file = os.path.isfile(os.path.join(self.base_path,p))
                if is_file and p.endswith('_index.html') is False:
                    print('>正在导入文档：',p)
                    self.get_content(p)
            print(">>>导入完成！")
        except Exception as e:
            print("[x]导入出现异常：")
            print(traceback.print_exc())

if __name__ == '__main__':
    print("""
  ______                          _         ___    __  __      _____             
 |  ____|                        | |       |__ \  |  \/  |    |  __ \            
 | |____   _____ _ __ _ __   ___ | |_ ___     ) | | \  / |_ __| |  | | ___   ___ 
 |  __\ \ / / _ \ '__| '_ \ / _ \| __/ _ \   / /  | |\/| | '__| |  | |/ _ \ / __|
 | |___\ V /  __/ |  | | | | (_) | ||  __/  / /_  | |  | | |  | |__| | (_) | (__ 
 |______\_/ \___|_|  |_| |_|\___/ \__\___| |____| |_|  |_|_|  |_____/ \___/ \___|

【印象笔记导出笔记本导入到觅思文档】 v20240428
    """)
    CONFIG = ConfigParser()
    CONFIG.read(os.path.join('./config.ini'), encoding='utf-8')

    MRDOC_URL = CONFIG.get("mrdoc", "url", fallback="")
    if MRDOC_URL == "":
        MRDOC_URL = input("1)请输入你的觅思文档地址:")
    else:
        print("1)你配置的觅思文档地址为：", MRDOC_URL)
    if MRDOC_URL.endswith("/"):
        MRDOC_URL = MRDOC_URL[:-1]

    MRDOC_TOKEN = CONFIG.get("mrdoc", "token", fallback="")
    if MRDOC_TOKEN == "":
        MRDOC_TOKEN = input("2)请输入你的觅思文档用户 Token:")
    else:
        print("2)你配置的觅思文档用户Token为:", MRDOC_TOKEN)

    BASE_PATH = CONFIG.get("mrdoc", "dir", fallback="")
    if BASE_PATH == "":
        BASE_PATH = input("3)请输入待导入文件夹路径:")
    else:
        print("3)你配置的待导入文件夹路径为:", BASE_PATH)

    if os.path.exists(BASE_PATH):
        op = Evernote2Mrdoc()
        op.work()
    else:
        print("[x]错误：目标文件夹不存在！")
    os.system('pause')